﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace VisionFrame.Base.Converter
{
    public class StringToNodeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string[] _info = value.ToString().Split(";");

            Assembly assembly = Assembly.GetEntryAssembly();
            Type type = assembly.GetType(_info[0]);
            if (_info.Length == 2)
            {
                assembly =
                    Assembly.LoadFile(Environment.CurrentDirectory + "/Activities/" + _info[0] + ".dll");
                if (assembly == null) return null;

                type = assembly.GetType(_info[1]);
                if (type == null) return null;
            }

            object instance = Activator.CreateInstance(type);

            Binding binding = new Binding("DataContext.AnchorDownCommand");
            binding.RelativeSource = new RelativeSource() { AncestorType = typeof(ItemsControl) };
            (instance as NodeBase).SetBinding(NodeBase.AnchorDownCommandProperty, binding);


            binding = new Binding("DataContext.AnchorUpCommand");
            binding.RelativeSource = new RelativeSource() { AncestorType = typeof(ItemsControl) };
            (instance as NodeBase).SetBinding(NodeBase.AnchorUpCommandProperty, binding);

            return instance;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}
